<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    width="800px"
    top="60px"
    @close="handleClose"
  >
    <!-- 表单 -->
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-position="right"
      label-width="88px"
      style="width: 400px; margin-left: 50px"
    >
      <el-form-item :label="$t('table.avatar')">
        <div class="avatar-container">
          <upload-avatar
            :avatarUrl="avatarUrl"
            @onChange="onChangeAvatar"
            @onRemove="onRemoveAvatar"
          />
        </div>
      </el-form-item>
      <el-form-item :label="$t('table.username')" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item
        :label="$t('table.password')"
        prop="password"
        v-if="dialogTitle === $t('dialog.addUser')"
      >
        <el-input v-model="form.password" type="password" />
      </el-form-item>
      <el-form-item :label="$t('table.nick_name')" prop="nick_name">
        <el-input v-model="form.nick_name" />
      </el-form-item>
      <el-form-item :label="$t('table.sex')">
        <el-radio-group v-model="form.sex">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('table.email')" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item :label="$t('table.mobile')" prop="mobile">
        <el-input v-model="form.mobile" />
      </el-form-item>
      <el-form-item :label="$t('table.create_time')" prop="create_time">
        <el-input v-model="form.create_time" disabled />
      </el-form-item>
      <el-form-item :label="$t('table.remark')" prop="remark">
        <el-input v-model="form.remark" />
      </el-form-item>
      <el-form-item :label="$t('table.status')" prop="status">
        <el-switch
          :active-value="1"
          :inactive-value="0"
          v-model="form.status"
          :disabled="form.is_admin ? true : false"
        />
      </el-form-item>
      <el-form-item :label="$t('table.is_admin')">
        <el-switch
          :active-value="1"
          :inactive-value="0"
          v-model="form.is_admin"
          disabled
        />
      </el-form-item>
    </el-form>

    <!-- 底部按钮组 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">{{ $t('dialog.Cancel') }}</el-button>
        <el-button type="primary" @click="handleConfirm">{{
          $t('dialog.Confirm')
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup name="Dialog">
import { ref, watch } from 'vue'
import { addUser, editUser, updateAvatar } from '@/api/user'
import { ElMessage } from 'element-plus'
// import { Plus } from '@element-plus/icons-vue'
import UploadAvatar from '@/components/UploadAvatar/index.vue'
import dayjs from 'dayjs'
import { apiUrl } from '@/utils/common.js'
import { useI18n } from 'vue-i18n'
const i18n = useI18n()

// 父组件传参
const props = defineProps({
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogTableValue: {
    type: Object,
    default: () => {}
  }
})

// 是否显示弹窗
const dialogVisible = ref(false)
const formRef = ref(null)
const form = ref({
  username: '',
  password: '',
  nick_name: '',
  sex: 1,
  email: '',
  mobile: '',
  avatar: '',
  create_time: '',
  status: 1,
  remark: '',
  is_admin: 0,
  is_delete: 0
})
const formAvatar = ref(null) // 选择后的文件
const upAvatarFlag = ref(false) // 头像状态
const avatarUrl = ref(null) // 头像上传成功后的地址
// 表单校验
const rules = ref({
  username: [
    {
      required: true,
      message: i18n.t('rules.username'),
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: i18n.t('rules.password'),
      trigger: 'blur'
    }
  ],
  nick_name: [
    {
      required: true,
      message: i18n.t('rules.nick_name'),
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: i18n.t('rules.email'),
      // message: 'Please input email address',
      trigger: 'blur'
    },
    {
      type: 'email',
      // message: 'Please input correct email address',
      message: i18n.t('rules.email_type'),
      trigger: ['blur', 'change']
    }
  ]
})
// 监听表单数据
watch(
  () => props.dialogTableValue,
  () => {
    if (props.dialogTitle === i18n.t('dialog.editUser')) {
      form.value = JSON.parse(JSON.stringify(props.dialogTableValue))
      avatarUrl.value = form.value.avatar ? apiUrl + form.value.avatar : null
    } else {
      form.value.sex = 1
      form.value.create_time = dayjs().format('YYYY-MM-DD HH:mm:ss')
      form.value.status = 1
    }
  },
  { deep: true, immediate: true }
)

const emits = defineEmits(['update:modelValue', 'initUserList'])

// 关闭
const handleClose = () => {
  emits('update:modelValue', false)
}

// 确认
const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    const isEdit = props.dialogTitle === i18n.t('dialog.editUser')
    if (valid) {
      const res = isEdit
        ? await editUser(form.value)
        : await addUser(form.value)

      if (res.status === 0) {
        props.dialogTitle === i18n.t('dialog.addUser') &&
          (form.value.id = res.data.insertId)
        // 添加头像或修改头像
        if (upAvatarFlag.value) {
          formAvatar.value.append('old_avatar', form.value.avatar || '')
          formAvatar.value.append('id', form.value.id || res.data.insertId)
          // 调用接口
          const upRes = await updateAvatar(formAvatar.value)
          if (upRes.status === 0) {
            upAvatarFlag.value = false // 头像上传成功后处理状态
            avatarUrl.value = apiUrl + upRes.avatar.avatarUrl
            ElMessage.success(
              isEdit
                ? i18n.t('message.updeteSuccess')
                : i18n.t('message.saveSuccess')
            )
            emits('initUserList')
            handleClose()
          } else {
            ElMessage.error(
              isEdit
                ? i18n.t('message.updeteFailed')
                : i18n.t('message.saveFailed')
            )
          }
        } else {
          ElMessage.success(
            isEdit
              ? i18n.t('message.updeteSuccess')
              : i18n.t('message.saveSuccess')
          )
          emits('initUserList')
          handleClose()
        }
      }
    } else {
      return false
    }
  })
}

// 选择头像后处理事件
const onChangeAvatar = (file) => {
  if (file) {
    formAvatar.value = new FormData()
    formAvatar.value.append('avatar', file)
    upAvatarFlag.value = true
  }
}
// 删除头像
const onRemoveAvatar = () => {
  formAvatar.value = null
  upAvatarFlag.value = false
}
</script>

<style lang="scss" scoped>
@import '../index.scss';
</style>

<style>
.el-overlay-dialog {
  overflow: hidden !important;
}
</style>
